/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * This file is part of retabel.
 *
 * Copyright (c) 2011 by individual contributors as indicated by the
 * @author tags. See the copyright.txt file in the distribution
 * for a full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

package org.retabel.service.render.exportable;

import org.apache.commons.lang.StringUtils;
import org.retabel.persistence.entity.document.SectionConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.xml.transform.*;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.net.URI;

/**
 * Parameter class to hold the information about section configurations and rendered content.
 * <p/>
 * <h3>Extra-Info</h3>
 * Created: 21:41 26.09.11
 *
 * @author Burt Parkers
 * @version 1.0
 */
public class FopExportableDocumentPart extends ExportableDocumentPart<Source> {

    /** The Logger. */
    private static final Logger logger = LoggerFactory.getLogger(FopExportableDocumentPart.class);

    private final URI reportDesignURI;
    private byte[] bytes;

    /**
     * Creates a parameter object.
     *
     * @param sectionConfiguration the section configuration.
     * @param reportDesignURI      the report design uri.
     */
    public FopExportableDocumentPart(SectionConfiguration sectionConfiguration, URI reportDesignURI) {
        super(sectionConfiguration);

        this.reportDesignURI = reportDesignURI;

    }

    public void fill(byte[] dataContent) throws Exception {

        String packageName = getSectionConfiguration().getReportDesign().getReportDesignPackage().getName();
        String version = getSectionConfiguration().getReportDesign().getReportDesignPackage().getVersion();
        String name = getSectionConfiguration().getReportDesign().getName();

        URI uri = reportDesignURI.resolve(StringUtils.join(new String[]{packageName, "/", version, "/", name}));

        Source xmlSource = new StreamSource(new ByteArrayInputStream(dataContent));
        Source xsltSource = new StreamSource(uri.toString());

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer(xsltSource);
        transformer.setErrorListener(new ErrorListener() {
            @Override
            public void warning(TransformerException exception) throws TransformerException {
                logger.warn(exception.getMessage(), exception);
            }

            @Override
            public void error(TransformerException exception) throws TransformerException {
                logger.warn(exception.getMessage(), exception);
            }

            @Override
            public void fatalError(TransformerException exception) throws TransformerException {
                logger.error(exception.getMessage(), exception);
            }
        });

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        StreamResult streamResult = new StreamResult(baos);

        logger.debug("XSLT transformation: {}", uri);

        transformer.transform(xmlSource, streamResult);

        bytes = baos.toByteArray();

        logger.debug("FO print: {}", bytes.length);
    }

    @Override
    public Source getRenderedContent() {
        if (bytes == null)
        {
            return null;
        }

        return new StreamSource(new ByteArrayInputStream(bytes));
    }
}
